package exam;

import utils.DBConnection;
import utils.TimeUtils;

import java.util.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-11-1
 * Time: 17:43:06
 */
public class ExamUtils {

  private static final int LENGTH = 2000;

  private static long getCount(Connection con) throws SQLException {
    String sql = "SELECT COUNT(*) AS count FROM answerpaper";
    ResultSet rs = con.createStatement().executeQuery(sql);
    return rs.next() ? rs.getLong("count") : -1;
  }

  public static void main(String[] args) throws Exception {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");

    Connection con = new DBConnection(DBConnection.AutoCommiteOn).getConnection();
    long count = getCount(con);
    if (count == -1) return;
    con.close();

    for (long c = 0; c < count + LENGTH; c += LENGTH) {
      con = new DBConnection(DBConnection.AutoCommiteOff).getConnection();
      System.out.println("transfering from " + c + " to " + (c + LENGTH));

      Map<String, List<AnswerPaperInfo>> amap = new HashMap<String, List<AnswerPaperInfo>>();
      String sql = "SELECT * FROM answerpaper LIMIT " + c + "," + LENGTH;
      Statement sta = con.createStatement();
      ResultSet rs = sta.executeQuery(sql);
      while (rs.next()) {
        AnswerPaperInfo ainfo = AnswerPaper.rs2Info(rs);

        TestPaperInfo tinfo = TestPaper.getTestPaperByTid(con, ainfo.getTid());
        String yyyyMM = dateFormat.format(new Date(tinfo.getDate()));

        List<AnswerPaperInfo> list = amap.get(yyyyMM);
        if (list == null) list = new ArrayList<AnswerPaperInfo>();
        list.add(ainfo);
        amap.put(yyyyMM, list);
      }

      for (String key : amap.keySet()) {
        long date = TimeUtils.GetMilsecTimeyyyyMM(key);
        AnswerPaper.dbCheck(con, date);

        List<AnswerPaperInfo> list = amap.get(key);
        AnswerPaper.addAnswerPaperList(con, date, list);
      }

      con.commit();
      con.close();
    }
  }
}
